$(function () {
    var initPage = function () {
        // 查询短信账户余额
        $.get("communicate/checkBalance", function (res) {
            $("#balanceValue").text(res + "元");
        });
    };
    // 初始化页面
    initPage();
    var fileName = $("#fileName"), document = null, content = $("#msg-content");
    /**
     * 初始化文件上传控件
     */
    var initUploader = function () {
        var doUploadBtn = $("#doUploadBtn"),
                upload_btn_default = '发送短信',
                upload_btn_process = '<i class="fa fa-spin fa-spinner mr10"></i>发送中...';
        /**
         * 弹出文件选择框
         */
        $('#upZone').click(function () {
            $('#fileInput').click();
        });
        $('#fileInput').on("change", function (e) {
            var files = e.target.files;
            if (!files.length || !window.FileReader) {
                return; // no file selected, or no FileReader support
            }
            document = files[0];
            console.log(document);
            if (/^text\/plain/.test(document.type)) {
                fileName.val(document.name.replace(".txt", ""));
                alert("上传成功！");
            } else {
                document = null;
                alert("文件格式不正确！请上传TXT格式文件");
            }
        });
        /**
         * 保存材料：触发上传
         */
        doUploadBtn.on("click", function () {
            if (document === null) {
                alert("尚未上传短信文件");
            } else {
                $('form[name=uploadForm]').trigger('submit');
            }
        });
        /**
         *  上传文件
         */
        $('form[name=uploadForm]').on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();
            var url = 'communicate/upload';
            var formData = new FormData();
            formData.append("file", document);
            formData.append("content", content.val());
            doUploadBtn.prop("disabled", true).html(upload_btn_process);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    doUploadBtn.html(upload_btn_default).prop("disabled", false);
                    if (res.success) {
                        alert("短信发送成功！");
                        location.reload();
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('发送失败：网络错误');
            });
        });
    };
    initUploader();
});
